import vue from '@vitejs/plugin-vue';
import { loadEnv, defineConfig } from 'vite';
import fs from 'fs';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import mockDevServerPlugin from 'vite-plugin-mock-dev-server';
import vueJsx from '@vitejs/plugin-vue-jsx';
import UnoCSS from 'unocss/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
import { viteCommonjs } from '@originjs/vite-plugin-commonjs';
import { visualizer } from 'rollup-plugin-visualizer';
import { resolve } from 'path';

// 读取 package.json 文件
const pkg = JSON.parse(
  fs.readFileSync(resolve(__dirname, './package.json'), 'utf-8'),
);
// 定义常量
const __APP_INFO__ = {
  pkg: {
    name: pkg.name,
    version: pkg.version,
    engines: pkg.engines,
    dependencies: pkg.dependencies,
    devDependencies: pkg.devDependencies,
  },
  buildTimestamp: Date.now(),
};

const pathSrc = resolve(__dirname, 'src');
const dev_mock = false;

// Vite配置  https://cn.vitejs.dev/config
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd());
  return {
    resolve: {
      alias: {
        '@': pathSrc,
      },
    },
    css: {
      preprocessorOptions: {
        // 定义全局 SCSS 变量
        scss: {
          javascriptEnabled: true,
          api: 'modern-compiler',
          additionalData: `
            @use "@/styles/variables.scss" as *;
          `,
        },
      },
    },
    server: {
      host: '0.0.0.0',
      port: 7025,
      open: true,
      proxy: {
        '/admin': {
          changeOrigin: true,
          target: env.VITE_APP_BASE_API,
          rewrite: (path) => path.replace(new RegExp('^' + '/admin'), '/admin'),
        },
        '/api': {
          changeOrigin: true,
          target: env.VITE_APP_BASE_API,
          rewrite: (path) => path.replace(new RegExp('^' + '/api'), '/api'),
        },
        '/docs': {
          changeOrigin: true,
          target: env.VITE_APP_BASE_API,
          rewrite: (path) => path.replace(new RegExp('^' + '/docs'), '/docs'),
        },
        '/upload': {
          changeOrigin: true,
          target: env.VITE_APP_BASE_API,
          rewrite: (path) =>
            path.replace(new RegExp('^' + '/upload'), '/upload'),
        },
      },
      hmr: {
        overlay: false,
      },
    },
    plugins: [
      vue(),
      visualizer({
        open: true,
        gzipSize: true, // 显示 gzip 压缩后的大小
        brotliSize: true, // 显示 brotli 压缩后的大小
      }),
      vueJsx(),
      dev_mock ? mockDevServerPlugin() : null,
      UnoCSS({
        hmrTopLevelAwait: false,
      }),
      viteCommonjs(),
      // 自动导入配置 https://github.com/sxzz/element-plus-best-practices/blob/main/vite.config.ts
      AutoImport({
        // 导入 Vue 函数，如：ref, reactive, toRef 等
        imports: ['vue', '@vueuse/core', 'pinia', 'vue-router', 'vue-i18n'],
        resolvers: [
          // 导入 Element Plus函数，如：ElMessage, ElMessageBox 等
          ElementPlusResolver(),
        ],
        vueTemplate: true,
        // 导入函数类型声明文件路径 (false:关闭自动生成)
        dts: false,
        // dts: "src/types/auto-imports.d.ts",
      }),
      Components({
        resolvers: [
          // 导入 Element Plus 组件
          ElementPlusResolver(),
        ],
        // 指定自定义组件位置(默认:src/components)
        dirs: [
          'src/components',
          'src/components/common',
          'src/components/raiseinfo',
          'src/components/dashboard',
          'src/**/components',
        ],
        // 导入组件类型声明文件路径 (false:关闭自动生成)
        dts: false,
        // dts: "src/types/components.d.ts",
      }),
      createSvgIconsPlugin({
        // 缓存图标位置
        iconDirs: [resolve(pathSrc, 'assets/icons')],
        symbolId: 'icon-[dir]-[name]',
      }),
    ],
    // 预加载项目必需的组件
    optimizeDeps: {
      include: [
        'vue',
        'vue-router',
        'pinia',
        'axios',
        '@vueuse/core',
        'sortablejs',
        'exceljs',
        'path-to-regexp',
        'echarts',
        '@wangeditor/editor',
        '@wangeditor/editor-for-vue',
        'vue-i18n',
        'path-browserify',
        'element-plus/es/components/form/style/css',
        'element-plus/es/components/form-item/style/css',
        'element-plus/es/components/button/style/css',
        'element-plus/es/components/input/style/css',
        'element-plus/es/components/input-number/style/css',
        'element-plus/es/components/switch/style/css',
        'element-plus/es/components/upload/style/css',
        'element-plus/es/components/menu/style/css',
        'element-plus/es/components/col/style/css',
        'element-plus/es/components/icon/style/css',
        'element-plus/es/components/row/style/css',
        'element-plus/es/components/tag/style/css',
        'element-plus/es/components/dialog/style/css',
        'element-plus/es/components/loading/style/css',
        'element-plus/es/components/radio/style/css',
        'element-plus/es/components/radio-group/style/css',
        'element-plus/es/components/popover/style/css',
        'element-plus/es/components/scrollbar/style/css',
        'element-plus/es/components/tooltip/style/css',
        'element-plus/es/components/dropdown/style/css',
        'element-plus/es/components/dropdown-menu/style/css',
        'element-plus/es/components/dropdown-item/style/css',
        'element-plus/es/components/sub-menu/style/css',
        'element-plus/es/components/menu-item/style/css',
        'element-plus/es/components/divider/style/css',
        'element-plus/es/components/card/style/css',
        'element-plus/es/components/link/style/css',
        'element-plus/es/components/breadcrumb/style/css',
        'element-plus/es/components/breadcrumb-item/style/css',
        'element-plus/es/components/table/style/css',
        'element-plus/es/components/tree-select/style/css',
        'element-plus/es/components/table-column/style/css',
        'element-plus/es/components/select/style/css',
        'element-plus/es/components/option/style/css',
        'element-plus/es/components/pagination/style/css',
        'element-plus/es/components/tree/style/css',
        'element-plus/es/components/alert/style/css',
        'element-plus/es/components/radio-button/style/css',
        'element-plus/es/components/checkbox-group/style/css',
        'element-plus/es/components/checkbox/style/css',
        'element-plus/es/components/tabs/style/css',
        'element-plus/es/components/tab-pane/style/css',
        'element-plus/es/components/rate/style/css',
        'element-plus/es/components/date-picker/style/css',
        'element-plus/es/components/notification/style/css',
        'element-plus/es/components/image/style/css',
        'element-plus/es/components/statistic/style/css',
        'element-plus/es/components/watermark/style/css',
        'element-plus/es/components/config-provider/style/css',
        'element-plus/es/components/text/style/css',
        'element-plus/es/components/drawer/style/css',
        'element-plus/es/components/color-picker/style/css',
        'element-plus/es/components/backtop/style/css',
        'element-plus/es/components/message-box/style/css',
        'element-plus/es/components/skeleton/style/css',
        'element-plus/es/components/skeleton-item/style/css',
        'element-plus/es/components/badge/style/css',
        'element-plus/es/components/steps/style/css',
        'element-plus/es/components/step/style/css',
        'element-plus/es/components/avatar/style/css',
        'element-plus/es/components/descriptions/style/css',
        'element-plus/es/components/descriptions-item/style/css',
        'element-plus/es/components/checkbox-group/style/css',
        'element-plus/es/components/progress/style/css',
        'element-plus/es/components/image-viewer/style/css',
        'element-plus/es/components/empty/style/css',
      ],
    },
    // 构建配置
    base: './',
    build: {
      outDir: '../public/dist', // 直接打包到 thinkphp 的 public 目录
      assetsDir: 'static', // 静态文件默认存储位置
      emptyOutDir: true, // 打包前清空目录
      chunkSizeWarningLimit: 2000, // 消除打包大小超过500kb警告
      minify: 'terser', // Vite 2.6.x 以上需要配置 minify: "terser", terserOptions 才能生效
      terserOptions: {
        compress: {
          keep_infinity: true, // 防止 Infinity 被压缩成 1/0，这可能会导致 Chrome 上的性能问题
          // drop_console: true, // 生产环境去除 console
          // drop_debugger: true, // 生产环境去除 debugger
        },
        format: {
          comments: false, // 删除注释
        },
      },
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes('node_modules')) {
              // 将体积较大的库单独打包
              if (id.includes('element-plus')) {
                return 'element-plus';
              }
              if (id.includes('echarts')) {
                return 'echarts';
              }
              if (id.includes('vue-i18n')) {
                return 'vue-i18n';
              }
              if (id.includes('vxe-pc-ui')) {
                return 'vxe-pc-ui';
              }
              if (id.includes('vxe-table')) {
                return 'vxe-table';
              }
              if (id.includes('xe-utils')) {
                return 'xe-utils';
              }
              if (id.includes('json-editor-vue3')) {
                return 'json-editor-vue3';
              }
              if (id.includes('mqtt')) {
                return 'mqtt';
              }
              if (id.includes('@kangc/v-md-editor')) {
                return 'v-md-editor';
              }
              if (id.includes('tinymce')) {
                return 'tinymce';
              }
              if (id.includes('wangeditor')) {
                return 'wangeditor';
              }
              if (id.includes('themes')) {
                return 'themes';
              }
              if (id.includes('axios')) {
                return 'axios';
              }
              if (id.includes('@vueuse/core')) {
                return 'vueuse-core';
              }
              if (id.includes('localforage')) {
                return 'localforage';
              }
              if (id.includes('jsencrypt')) {
                return 'jsencrypt';
              }
              if (id.includes('lodash-es')) {
                return 'lodash-es';
              }
              if (id.includes('jsoneditor')) {
                return 'jsoneditor';
              }
              // 将其他的 node_modules 依赖打包到 vendor chunk 中
              return 'vendor';
            }
          },
          // 用于从入口点创建的块的打包输出格式[name]表示文件名,[hash]表示该文件内容hash值
          entryFileNames: 'static/js/[name].[hash].js',
          // 用于命名代码拆分时创建的共享块的输出命名
          chunkFileNames: 'static/js/[name].[hash].js',
          // 用于输出静态资源的命名，[ext]表示文件扩展名
          assetFileNames: (assetInfo) => {
            const info = assetInfo.name.split('.');
            let extType = info[info.length - 1];
            if (
              /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/i.test(assetInfo.name)
            ) {
              extType = 'media';
            } else if (/\.(png|jpe?g|gif|svg)(\?.*)?$/.test(assetInfo.name)) {
              extType = 'img';
            } else if (/\.(woff2?|eot|ttf|otf)(\?.*)?$/i.test(assetInfo.name)) {
              extType = 'fonts';
            }
            return `static/${extType}/[name].[hash].[ext]`;
          },
        },
      },
    },
    define: {
      __APP_INFO__: JSON.stringify(__APP_INFO__),
    },
  };
});
